import { WebSocketServer as WSServer } from 'ws';
import { ConnectionConfig } from '../ConfigLoader';
import MessageHandler from '../MessageHandler';

export default class WebSocketServer {

    
  private heartbeatInterval?: NodeJS.Timeout;
  private heartbeatIntervalMs: number = 5000; // 默认5秒心跳间隔

  
  private server!: WSServer;
  private handler: MessageHandler;

  constructor(private config: ConnectionConfig, handler: MessageHandler) {
    this.handler = handler;
  }

  start() {
    const port = this.config.ws.server.port;
    this.server = new WSServer({ port });

    this.server.on('listening', () => {
      console.log(`[WS Server] 已启动在端口 ${port}`);
    });

    this.server.on('connection', (ws, req) => {
      const token = this.extractTokenFromRequest(req);
      if (!token || token !== this.config.token) {
        console.warn(`[WS Server] 无效 token 连接尝试: ${token || '无token'}`);
        ws.close(1008, '无效 token'); // 1008 = Policy Violation
        return;
      }

      ws.on('message', (message) => {
        this.handler.processMessage(message, 'server', ws);
      });
    });
  }
    // 从请求中提取 token
    private extractTokenFromRequest(req: any): string | null {
      try {
        return this.extractBearerToken(req.headers.authorization);
      } catch (error) {
        console.error('[WS Server] 解析URL失败:', error);
        return null;
      }
    }

    private extractBearerToken(authHeader: string | undefined | null): string | null {
        if (!authHeader) {
            return null;
        }
    
        // 移除首尾空格并按空格分割
        const parts = authHeader.trim().split(/\s+/);
        
        // 验证格式是否为 "Bearer <token>"
        if (parts.length !== 2 || parts[0].toLowerCase() !== 'bearer') {
            return null;
        }
    
        return parts[1] || null;
    }
}